<template>
    <div>
        <!-- 三级分类全局组件 -->
        <Category :scene="scene"></Category>
        <el-card style="margin: 10px 0;">
            <div v-show="scene==0">
                <el-button type="primary" size="default" icon="Plus" :disabled="categoryStore.c3Id?false:true" @click="addAttr">添加属性</el-button>
                <el-table border  style="margin: 10px 0;" :data="attrArr">
                    <el-table-column label="序号" type="index" align="center" width="80px"></el-table-column>
                    <el-table-column label="属性名称" width="120px" prop="attrName"></el-table-column>
                    <el-table-column label="属性值名称">
                        <template #="{row,$index}">
                            <el-tag style="margin: 5px;" v-for="(item,index) in row.attrValueList" :key="item.id">{{ item.valueName }}</el-tag>
                        </template>
                    </el-table-column>
                    <el-table-column label="操作" width="120px">
                        <template #="{row,$index}">
                            <el-button type="primary" size="small" icon="Edit" @click="updateAttr(row)"></el-button>
                            <el-popconfirm :title="`你确定删除${row.attrName}?`" width="200px" @confirm="deleteAttr(row.id)">
                                <template #reference>
                                    <el-button type="primary" size="small" icon="Delete"></el-button>
                                </template>
                            </el-popconfirm>
                        </template>
                    </el-table-column>
                </el-table>
            </div>
            <!-- 展示添加属性与修改属性 -->
            <div v-show="scene==1">
                <el-form :inline="true"> 
                    <el-form-item label="属性名称">
                        <el-input placeholder="请你输入属性的名称" v-model="attrParams.attrName"></el-input>
                    </el-form-item>
                </el-form>
                <el-button @click="addAttrValue" :disabled="attrParams.attrName?false:true" type="primary" size="default" icon="Plus">添加属性值</el-button>
                <el-button type="primary" size="default" @click="cancel">取消</el-button>
                <el-table border style="margin: 10px 0;" :data="attrParams.attrValueList">
                    <el-table-column width="80px" align="center" type="index" label="序号"></el-table-column>
                    <el-table-column label="属性值的名称">
                        <template #="{row,$index}">
                            <el-input :ref="(vc:any)=>inputArr[$index] = vc" v-if="row.flag" @blur="toLook(row,$index)" placeholder="请你输入属性值名称" v-model="row.valueName"></el-input>
                            <div v-else @click="toEdit(row,$index)">{{ row.valueName  }}</div>
                        </template>
                    </el-table-column>
                    <el-table-column label="属性值操作">
                        <template #="{row,$index}">
                            <el-button type="primary" size="small" icon="Delete" @click="attrParams.attrValueList.splice($index,1)"></el-button>

                        </template>
                    </el-table-column>
                </el-table>
                <el-button type="primary" size="default" @click="save" :disabled="attrParams.attrValueList.length>0?false:true">保存</el-button>
                <el-button type="primary" size="default" @click="cancel">取消</el-button>
            </div>
        </el-card>
    </div>
</template>
<script setup lang="ts">
import { ElMessage } from 'element-plus'
import { watch,ref,reactive,nextTick ,onBeforeUnmount} from 'vue';
import {reqAttr,reqAddOrUpdateAttr,reqRemoveAttr} from '@/api/product/attr/index'
import useCategoryStore from '@/store/modules/category';
import type {AttrResponseData,Attr,AttrValue} from '@/api/product/attr/type'
let categoryStore = useCategoryStore()
let attrArr = ref<Attr[]>([])
// 定义卡片的变换切换 0 table
let scene = ref<number>(0)
let attrParams = reactive<Attr>({
    attrName:'',
    attrValueList:[],
    categoryId:'',
    categoryLevel:3
})
let inputArr = ref<any>([])
watch(()=>categoryStore.c3Id,()=>{
    // 清空上一次查询的属性与属性值
    attrArr.value = []
    // 保证三级分类有才发请求
    if(!categoryStore.c3Id) return;
    getAttr()
})
// 获取已有的属性与属性值的方法
const getAttr = async () =>{
    // 获取分类的id
    const {c1Id,c2Id,c3Id} = categoryStore
    let result:AttrResponseData = await reqAttr(c1Id,c2Id,c3Id)
    if(result.code == 200){
        attrArr.value = result.data
    }
}
// 添加属性
const addAttr = ()=>{
    Object.assign(attrParams,{
    attrName:'',
    attrValueList:[],
    categoryId:categoryStore.c3Id,
    categoryLevel:3
    })
    scene.value = 1
}
const updateAttr = (row:Attr)=>{
    scene.value = 1
    // 浅拷贝 有问题
    // Object.assign(attrParams,row)
    // 深拷贝
    Object.assign(attrParams,JSON.parse(JSON.stringify(row)))
}
const cancel =()=>{
    scene.value = 0
}
// 添加属性值
const addAttrValue = ()=>{
    attrParams.attrValueList.push({
        valueName:'', 
        flag:true,//控制每一个属性值编辑模式与切换模式的切换
    })
    // 获取最后的el-input组件聚焦
    nextTick(()=>{
        inputArr.value[attrParams.attrValueList.length - 1].focus()
    })
}
const save =async () => {
    let result:any =await reqAddOrUpdateAttr(attrParams)
    if(result.code == 200){
        scene.value = 0
        ElMessage({
            type:'success',
            message:attrParams.id ? '修改成功' : '添加成功'
        })
        getAttr()
    }else{ 
        ElMessage({
            type:'error',
            message:attrParams.id ? '修改失败' : '添加失败'
        })
    }
}
const toLook = (row:AttrValue,$index:number)=>{
    // 非法情况判断1
    if(row.valueName.trim() == ''){
        attrParams.attrValueList.splice($index,1)
        ElMessage({
            type:'error',
            message:'属性值不能为空'
        })
        return;
    }
    // 非法情况2
    let repeat = attrParams.attrValueList.find((item)=>{
        // 切记把当前失去焦点属性值对象从当前数组扣除
        if(item!=row){
            return item.valueName === row.valueName
        }
    })
    if(repeat){
        attrParams.attrValueList.splice($index,1)
        ElMessage({
            type:'error',
            message:'属性值不能重复'
        })
        return;
    }
    row.flag = false
}
const toEdit = (row:AttrValue,$index:number)=>{
    row.flag = true
    nextTick(()=>{
        inputArr.value[$index].focus()
    })
}
const deleteAttr =async (attrId:number) => {
    let result:any = await reqRemoveAttr(attrId)
    if(result.code == 200){
        ElMessage({
            type:'success',
            message:'删除成功'
        })
        getAttr()
    }else{
        ElMessage({
            type:'error',
            message:'删除失败'
        })
    }
}
onBeforeUnmount(()=>{
    // 清空分类仓库的数据
    categoryStore.$reset()
})
</script>